﻿package tools;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriterEnhance {

	private String filename;
	private String encoding = "GB18030";

	public FileWriterEnhance(String filename) {
		this.filename = filename;
	}
	/**
	 * 
	 * @param filename
	 * @param encoding
	 */
	public FileWriterEnhance(String filename, String encoding) {
		this.filename = filename;
		this.encoding = encoding;
	}

	/**
	 * 
	 * @param content
	 */
	public void WriteToFile(String content) {
		File file = new File(filename);
		System.err.println("Writing file: " + file.getAbsolutePath());
		if (file.exists()) {
			System.err.println("Deleting old files!");
			file.delete();
		}

		File tempfile = new File(file.getParent());

		if (!tempfile.exists()) {
			tempfile.mkdirs();
		}

		try {
			DataOutputStream outs = new DataOutputStream(new FileOutputStream(
					file));
			outs.write(content.getBytes(encoding));
			outs.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param bytes
	 */
	public void WriteToFile(byte[] bytes) {
		File file = new File(filename);
		System.err.println("Writing file: " + file.getAbsolutePath());
		if (file.exists()) {
			System.err.println("Deleting old files!");
			file.delete();
		}
		
		File tempfile = new File(file.getParent());
		
		if (!tempfile.exists()) {
			tempfile.mkdirs();
		}
		
		try {
			DataOutputStream outs = new DataOutputStream(new FileOutputStream(
					file));
			outs.write(bytes);
			outs.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}